$(function(){

	var type = "hour";
	//初始化图表
	$('span[data-id="chart-hour"]').addClass("current").siblings("span").removeClass("current");
	
	query(type);
	
	setInterval(() => {
		query(type);
		$.post("/user/homeData",{type:type},function(data){
			
			$("#runMine").text(data.runMine);
			$("#totalMine").text(data.totalMine);
			$("#sumEarn").text(data.sumEarn);
			$("#income24").text(data.income24);
			$("#totalIncome").text(data.totalIncome);
			if(null!=data.accountAcceptDto){
				$("#speed1m").text(data.accountAcceptDto.speed1m);
				$("#speed5m").text(data.accountAcceptDto.speed5m);
				$("#speed15m").text(data.accountAcceptDto.speed15m);
				$("#speed1h").text(data.accountAcceptDto.speed1h);
			}
			
		},'json');
	}, 1000*60*5);
	
	
	function query(type){
		$.ajax({
			type : "post",
			// async:false,
			url:'/user/speedData?type='+type,
			dataType : "json",
			success : function(jsonData){ 
				createChart("chart-"+type,jsonData);
				$("#chart-"+type).show();
			},
			error: function(err){ 
				rtnData = [];
			},
		}); 
	}

	//图表按钮点击切换
	var btns = $(".J-btn-dashbord").find("span");
	$.each(btns, function(i,v){
		var chartId = $(v).attr("data-id");
		var _type = chartId.split("-")[1];
		$(v).on("click", function(){
            $(v).addClass("current").siblings("span").removeClass("current");
            type = _type;
            //初始化图表
			$.ajax({
		        type : "post",
		       // async:false,
		        url:'/user/speedData?type='+_type,
		        dataType : "json",
		        success : function(jsonData){ 
		        	 createChart(chartId,jsonData,_type);
		             $("#"+chartId).show().siblings("div").hide();
		        },
		        error: function(err){ 
		           rtnData = [];
		        },
		   }); 
		});
	});

});
	
function getChartData(type){
    var rtnData ;
    $.ajax({
         type : "post", //jquey是不支持post方式跨域的
        // async:false,
         url:'/user/speedData?type='+type,
         dataType : "json",
         success : function(jsonData){ 
               rtnData = jsonData;
         },
         error: function(err){ 
            rtnData = [];
         },
    }); 
    return rtnData;
}

//创建图表 createChart();
function createChart(id,chartData,type){
	//echart 
	var seriesdata = doSeriesData(chartData);
	var option = {
			color:['#31c3c1', '#bbcff7'],
	    tooltip : [{
	        trigger: 'axis',
	        formatter: function(params){
        		var len = params.length;
	            var nm = params[0].name;
	            var str = "<b style='color:#fff'>Pool Hashrate</b></br>";
	                str += nm+"</br>";
	            
	            for(var i=0; i<len; i++){
	            	if(nm != params[i].name){
	            		str += nm+"</br>";
	            		str += params[i].seriesName+':'+params[i].data;
	            		str += seriesdata.tooltip[params[i].seriesName] + '<br/>';
	            	}else{
	            		str += params[i].seriesName+':'+params[i].data;
	            		str += seriesdata.tooltip[params[i].seriesName] + '<br/>';
	            	}
	                
	              nm = params[i].name;
	            }
	
	            return str;
	        },
	        axisPointer:{
					    type: 'line',
					    lineStyle: {
					        color: '#1a1a1e',
					        width: 1,
					        type: 'solid'
					    }
					},

	    }],
	    legend: {
	    	show:false,
	        data:['BTC','LTC','ETH'],
	        textStyle:{
	            color:'#fff'
	        },

	    },
	    toolbox: {
	        show : false
	    },
	    calculable : true,
	    xAxis:doXaiseData(type),
	    yAxis : [
	        {
        	  name : 'T/s',
	          type : 'value',
            axisLabel: {
            	textStyle: {
							    color: '#929292'
							}
            },
            axisTick:{
            	show:true,
            	lineStyle: {
						    // 使用深浅的间隔色
						    color: '#c5c5c5'
						  }
            },
            axisLine:{
            	show:true,
            	lineStyle: {
						    // 使用深浅的间隔色
						    color: '#c5c5c5'
						  }
            },
	         	splitLine: {
	         			show:false,
						    lineStyle: {
						        // 使用深浅的间隔色
						        color: 'rgba(255,255,255,.1)'
						    }
						},

	        }
	    ],
	    series:seriesdata.series
	};
	//初始化图表
  var chartEle = $("#"+id)[0];
  if(chartEle){
		var myChart = echarts.init(chartEle);                  
		myChart.setOption(option);
	}
	//处理X轴数据
	function doXaiseData(type){
		var rtnData =[
	        {
	        	name : '      UTC+0:00',
	            type : 'category',
	            boundaryGap : false,
	            axisLabel:{
		            	interval:'auto',
		            	rotate:0,
		            	textStyle: {
								    color: '#929292'
								}
	            },
	            axisTick:{
	            	show:true,
	            	lineStyle: {
						        // 使用深浅的间隔色
						        color: '#929292'
						    }
	            },
	            axisLine:{
	            	show:true,
	            	lineStyle: {
						        // 使用深浅的间隔色
						        color: '#c5c5c5'
						    }
	            },
	            splitLine: {
	            		show:false,
							    lineStyle: {
							        // 使用深浅的间隔色
							        color: 'rgba(255,255,255,.1)'
							    }
							},
	            data:[]
	        }
	    ]
		if(seriesdata.series.length>0){
			var timeArr = seriesdata.series[0].time;
			var timeMax = getMax(timeArr);
			var timeMin = getMin(timeArr);

			if(timeArr){
				var len = timeArr.length;
				if(len > 10){
					if( type == "minute" ){
						rtnData[0].axisLabel.interval = 18;
					}else{
						rtnData[0].axisLabel.interval = 9;
					}
				}
				
				/*var pattern = "yyyy-MM-dd HH:mm:ss";
				if(len > 24){
					pattern = "yyyy-MM-dd";
				}*/
				for(var i=0; i<len; i++){
					//var time = timetodate(timeArr[i],pattern);
					//var timeV = time.split(",")[1].split(":")[0];
					var time = timeArr[i];
					if(time.length==8){
						time = time.substring(0,4)+"-"+time.substring(4,6)+"-"+time.substring(6,8);
					}else{
						time = time.substring(0,4)+"-"+time.substring(4,6)+"-"+time.substring(6,8)+" "+time.substring(8,10)+":00:00";
					}
					rtnData[0].data.push(time);
				}
			}
		}
		return rtnData;
	};
	//处理图表数据
	function doSeriesData(data){
		var rtnData = {
			series:[],
			tooltip:{},
		}
		var dd = {};	
		$.each(data.speedData, function(i,v){
			dd = {
	            name:v.coin,
	            type:'line',
	            smooth:true,
	           // itemStyle: {normal: {areaStyle: {type: 'default'}}},
	            //areaStyle: {show:false},
	            symbolSize:8,
              areaStyle: {
                  normal: {
                      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                          offset: 0,
                          color: '#31c3c1'
                      }, {
                          offset: 1,
                          color: '#bbcff7'
                      }])
                  }
              },
              markpoint:{
                  symbol:'circle',
                  symbolSize:8,
              },
	            time:doVData(v.poolSpeedBeanList).time,
	            data:doVData(v.poolSpeedBeanList).data
			}
			rtnData['series'].push(dd);
			rtnData['tooltip'][v.coin] = v.unit;
		});
		return rtnData;
	}
	function doVData(vData){
		var rtnData = {
			"time":[],
			"data":[]
		};
		
		$.each(vData, function(i,v){
			rtnData.time.push(v.date);
			rtnData.data.push(v.speed);
		});
		return rtnData;
	};
	function  timetodate(tim,dat){
  	Date.prototype.pattern=function(fmt) {       
     var o = {        
     "M+" : this.getMonth()+1,     
     "d+" : this.getDate(),     
     "h+" : this.getHours() == 0 ? 24 : this.getHours(),     
     "H+" : this.getHours(),      
     "m+" : this.getMinutes(),  
     "s+" : this.getSeconds(),     
     "q+" : Math.floor((this.getMonth()+3)/3),   
     "S" : this.getMilliseconds()      
     };       
     var week = {       
     "0" : "\u65e5",       
     "1" : "\u4e00",       
     "2" : "\u4e8c",       
     "3" : "\u4e09",       
     "4" : "\u56db",       
     "5" : "\u4e94",       
     "6" : "\u516d"      
     };      
 
     if(/(y+)/.test(fmt)){       
         fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));       
     }      
 
     if(/(E+)/.test(fmt)){       
         fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "\u661f\u671f" : "\u5468") : "")+week[this.getDay()+""]);       
     }       

     for(var k in o){       
         if(new RegExp("("+ k +")").test(fmt)){       
             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));       
         }       
     }       
     return fmt;       
  }
	 // return  new Date(parseInt(tim)*1000).pattern(dat);//"yyyy/MM/dd,hh,mm,ss"
	 return  new Date(parseInt(tim)).pattern(dat);//"yyyy/MM/dd,hh,mm,ss"    
	}
	function getMax(data){
		Array.prototype.max = function() {
			return Math.max.apply({},this)
		}
		return data.max();
	};
	function getMin(data){
		Array.prototype.min = function() {
			return Math.min.apply({},this)
		}
		return data.min();
	};
};

	

